import type { EventHandler, EventHandlerRequest } from 'h3'

export interface Response {
  message: string
  code: number
  result?: any
}

const success = (result: any): Response => {
  const resp: Response = {
    message: 'OK',
    code: 200
  }
  if (result != null) {
    resp.result = result
  }
  return resp
}

const failure = (err: Error): Response => {
  const resp: Response = {
    message: err.message,
    code: 500
  }
  return resp
}

export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D> (
  handler: EventHandler<T, D>
): EventHandler<T, D> => {
  return defineEventHandler<T>(async(event) => {
    if (event.node.req.method !== 'POST') {
      return failure(new Error('仅支持POST请求'))
    }
    try {
      const response = await handler(event)
      return success(response)
    } catch (err: any) {
      return failure(err)
    }
  })
}
  